{% extends 'base.html' %}

{% block title %}{% if supplier %}编辑供应商{% else %}新增供应商{% endif %} - 固定资产管理系统{% endblock %}

{% block extra_css %}
<style>
.file-upload-area {
    border: 2px dashed #dee2e6;
    border-radius: 8px;
    padding: 30px;
    text-align: center;
    background-color: #f8f9fa;
    transition: all 0.3s ease;
    cursor: pointer;
}

.file-upload-area:hover {
    border-color: #007bff;
    background-color: #e3f2fd;
}

.file-upload-area.dragover {
    border-color: #007bff;
    background-color: #e3f2fd;
    transform: scale(1.02);
}

.file-item {
    background: #f8f9fa;
    border: 1px solid #dee2e6;
    border-radius: 6px;
    padding: 12px;
    margin-bottom: 8px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.file-info {
    display: flex;
    align-items: center;
    flex-grow: 1;
}

.file-icon {
    font-size: 1.5rem;
    margin-right: 12px;
    width: 30px;
    text-align: center;
}

.file-details h6 {
    margin: 0;
    font-size: 0.9rem;
}

.file-details small {
    color: #6c757d;
}

.btn-remove-file {
    background: none;
    border: none;
    color: #dc3545;
    font-size: 1.1rem;
    cursor: pointer;
    padding: 4px 8px;
    border-radius: 4px;
    transition: background-color 0.2s;
}

.btn-remove-file:hover {
    background-color: #f5c6cb;
}

.form-section {
    background: #fff;
    border: 1px solid #dee2e6;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
}

.form-section h5 {
    color: #495057;
    border-bottom: 2px solid #007bff;
    padding-bottom: 8px;
    margin-bottom: 20px;
}

.required-field::after {
    content: " *";
    color: #dc3545;
}
</style>
{% endblock %}

{% block content %}
<div class="row">
    <div class="col-md-12">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="{% url 'assets:index' %}">首页</a></li>
                <li class="breadcrumb-item"><a href="{% url 'assets:supplier_list' %}">供应商管理</a></li>
                <li class="breadcrumb-item active" aria-current="page">{% if supplier %}编辑供应商{% else %}新增供应商{% endif %}</li>
            </ol>
        </nav>
        
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2><i class="fas fa-truck me-2"></i>{% if supplier %}编辑供应商{% else %}新增供应商{% endif %}</h2>
            <div class="btn-group">
                <a href="{% url 'assets:supplier_list' %}" class="btn btn-outline-secondary">
                    <i class="fas fa-arrow-left me-1"></i>返回列表
                </a>
                {% if supplier %}
                <a href="{% url 'assets:supplier_detail' supplier.pk %}" class="btn btn-outline-info">
                    <i class="fas fa-eye me-1"></i>查看详情
                </a>
                {% endif %}
            </div>
        </div>
        
        <form method="post" enctype="multipart/form-data" id="supplierForm">
    {% csrf_token %}

    {% if supplier_form.errors %}
    <div class="alert alert-danger" role="alert">
        请修正以下错误：
        <ul>
            {% for field in supplier_form %}
                {% if field.errors %}
                    {% for error in field.errors %}
                        <li>{{ field.label }}: {{ error }}</li>
                    {% endfor %}
                {% endif %}
            {% endfor %}
            {% for error in supplier_form.non_field_errors %}
                <li>{{ error }}</li>
            {% endfor %}
        </ul>
    </div>
    {% endif %}

    <!-- 基本信息 -->
    <div class="form-section">
        <h5><i class="fas fa-info-circle me-2"></i>基本信息</h5>
        <div class="row">
            <div class="col-md-6">
                <div class="mb-3">
                    <label for="{{ supplier_form.name.id_for_label }}" class="form-label required-field">供应商名称</label>
                    {{ supplier_form.name }}
                    {% if supplier_form.name.errors %}<div class="invalid-feedback d-block">{% for error in supplier_form.name.errors %}{{ error }}{% endfor %}</div>{% endif %}
                </div>
            </div>
            <div class="col-md-6">
                <div class="mb-3">
                    <label for="{{ supplier_form.supplier_type.id_for_label }}" class="form-label">供应商类型</label>
                    {{ supplier_form.supplier_type }}
                    {% if supplier_form.supplier_type.errors %}<div class="invalid-feedback d-block">{% for error in supplier_form.supplier_type.errors %}{{ error }}{% endfor %}</div>{% endif %}
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-md-6">
                <div class="mb-3">
                    <label for="{{ supplier_form.credit_code.id_for_label }}" class="form-label">统一社会信用代码</label>
                    {{ supplier_form.credit_code }}
                    {% if supplier_form.credit_code.errors %}<div class="invalid-feedback d-block">{% for error in supplier_form.credit_code.errors %}{{ error }}{% endfor %}</div>{% endif %}
                </div>
            </div>
            <div class="col-md-6">
                <div class="mb-3">
                    <label for="{{ supplier_form.legal_representative.id_for_label }}" class="form-label">法定代表人</label>
                    {{ supplier_form.legal_representative }}
                    {% if supplier_form.legal_representative.errors %}<div class="invalid-feedback d-block">{% for error in supplier_form.legal_representative.errors %}{{ error }}{% endfor %}</div>{% endif %}
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-md-6">
                <div class="mb-3">
                    <label for="{{ supplier_form.registration_address.id_for_label }}" class="form-label">注册地址</label>
                    {{ supplier_form.registration_address }}
                    {% if supplier_form.registration_address.errors %}<div class="invalid-feedback d-block">{% for error in supplier_form.registration_address.errors %}{{ error }}{% endfor %}</div>{% endif %}
                </div>
            </div>
            <div class="col-md-6">
                <div class="mb-3">
                    <label for="{{ supplier_form.business_scope.id_for_label }}" class="form-label">经营范围</label>
                    {{ supplier_form.business_scope }}
                    {% if supplier_form.business_scope.errors %}<div class="invalid-feedback d-block">{% for error in supplier_form.business_scope.errors %}{{ error }}{% endfor %}</div>{% endif %}
                </div>
            </div>
        </div>
    </div>

    <!-- 联系信息 -->
    <div class="form-section">
        <h5><i class="fas fa-address-book me-2"></i>联系信息</h5>
        <div class="row">
            <div class="col-md-6">
                <div class="mb-3">
                    <label for="{{ supplier_form.contact_person.id_for_label }}" class="form-label">联系人</label>
                    {{ supplier_form.contact_person }}
                    {% if supplier_form.contact_person.errors %}<div class="invalid-feedback d-block">{% for error in supplier_form.contact_person.errors %}{{ error }}{% endfor %}</div>{% endif %}
                </div>
            </div>
            <div class="col-md-6">
                <div class="mb-3">
                    <label for="{{ supplier_form.contact_position.id_for_label }}" class="form-label">联系人职位</label>
                    {{ supplier_form.contact_position }}
                    {% if supplier_form.contact_position.errors %}<div class="invalid-feedback d-block">{% for error in supplier_form.contact_position.errors %}{{ error }}{% endfor %}</div>{% endif %}
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-md-4">
                <div class="mb-3">
                    <label for="{{ supplier_form.phone.id_for_label }}" class="form-label">联系电话</label>
                    {{ supplier_form.phone }}
                    {% if supplier_form.phone.errors %}<div class="invalid-feedback d-block">{% for error in supplier_form.phone.errors %}{{ error }}{% endfor %}</div>{% endif %}
                </div>
            </div>
            <div class="col-md-4">
                <div class="mb-3">
                    <label for="{{ supplier_form.mobile.id_for_label }}" class="form-label">手机号码</label>
                    {{ supplier_form.mobile }}
                    {% if supplier_form.mobile.errors %}<div class="invalid-feedback d-block">{% for error in supplier_form.mobile.errors %}{{ error }}{% endfor %}</div>{% endif %}
                </div>
            </div>
            <div class="col-md-4">
                <div class="mb-3">
                    <label for="{{ supplier_form.fax.id_for_label }}" class="form-label">传真号码</label>
                    {{ supplier_form.fax }}
                    {% if supplier_form.fax.errors %}<div class="invalid-feedback d-block">{% for error in supplier_form.fax.errors %}{{ error }}{% endfor %}</div>{% endif %}
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-md-6">
                <div class="mb-3">
                    <label for="{{ supplier_form.email.id_for_label }}" class="form-label">邮箱地址</label>
                    {{ supplier_form.email }}
                    {% if supplier_form.email.errors %}<div class="invalid-feedback d-block">{% for error in supplier_form.email.errors %}{{ error }}{% endfor %}</div>{% endif %}
                </div>
            </div>
            <div class="col-md-6">
                <div class="mb-3">
                    <label for="{{ supplier_form.website.id_for_label }}" class="form-label">官方网站</label>
                    {{ supplier_form.website }}
                    {% if supplier_form.website.errors %}<div class="invalid-feedback d-block">{% for error in supplier_form.website.errors %}{{ error }}{% endfor %}</div>{% endif %}
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-md-8">
                <div class="mb-3">
                    <label for="{{ supplier_form.address.id_for_label }}" class="form-label">联系地址</label>
                    {{ supplier_form.address }}
                    {% if supplier_form.address.errors %}<div class="invalid-feedback d-block">{% for error in supplier_form.address.errors %}{{ error }}{% endfor %}</div>{% endif %}
                </div>
            </div>
            <div class="col-md-4">
                <div class="mb-3">
                    <label for="{{ supplier_form.postal_code.id_for_label }}" class="form-label">邮政编码</label>
                    {{ supplier_form.postal_code }}
                    {% if supplier_form.postal_code.errors %}<div class="invalid-feedback d-block">{% for error in supplier_form.postal_code.errors %}{{ error }}{% endfor %}</div>{% endif %}
                </div>
            </div>
        </div>
    </div>

    <!-- 银行信息 -->
    <div class="form-section">
        <h5><i class="fas fa-university me-2"></i>银行信息</h5>
        <div class="row">
            <div class="col-md-6">
                <div class="mb-3">
                    <label for="{{ supplier_form.bank_name.id_for_label }}" class="form-label">开户银行</label>
                    {{ supplier_form.bank_name }}
                    {% if supplier_form.bank_name.errors %}<div class="invalid-feedback d-block">{% for error in supplier_form.bank_name.errors %}{{ error }}{% endfor %}</div>{% endif %}
                </div>
            </div>
            <div class="col-md-6">
                <div class="mb-3">
                    <label for="{{ supplier_form.bank_account.id_for_label }}" class="form-label">银行账号</label>
                    {{ supplier_form.bank_account }}
                    {% if supplier_form.bank_account.errors %}<div class="invalid-feedback d-block">{% for error in supplier_form.bank_account.errors %}{{ error }}{% endfor %}</div>{% endif %}
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-md-12">
                <div class="mb-3">
                    <label for="{{ supplier_form.bank_address.id_for_label }}" class="form-label">开户行地址</label>
                    {{ supplier_form.bank_address }}
                    {% if supplier_form.bank_address.errors %}<div class="invalid-feedback d-block">{% for error in supplier_form.bank_address.errors %}{{ error }}{% endfor %}</div>{% endif %}
                </div>
            </div>
        </div>
    </div>

    <!-- 文件上传 -->
    <div class="form-section">
        <h5><i class="fas fa-file-upload me-2"></i>文件上传</h5>
        
        <!-- 营业执照上传 -->
        <div class="mb-4">
            <label for="{{ supplier_form.business_license.id_for_label }}" class="form-label">营业执照</label>
            {% if supplier.business_license %}
            <div class="file-item mt-3" id="currentLicense">
                <div class="file-info">
                    <i class="fas fa-file-pdf file-icon text-danger"></i>
                    <div class="file-details">
                        <h6>当前营业执照</h6>
                        <small>{{ supplier.business_license.name|default:"营业执照文件" }}</small>
                    </div>
                </div>
                <div>
                    <a href="{{ supplier.business_license.url }}" target="_blank" class="btn btn-sm btn-outline-primary me-2">
                        <i class="fas fa-eye"></i> 查看
                    </a>
                    <button type="button" class="btn-remove-file" onclick="removeLicense()">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </div>
            {% endif %}
            {{ supplier_form.business_license }}
            {% if supplier_form.business_license.errors %}<div class="invalid-feedback d-block">{% for error in supplier_form.business_license.errors %}{{ error }}{% endfor %}</div>{% endif %}
        </div>
        
        <!-- 其他资质文件上传 -->
        <div class="mb-4">
            <label class="form-label">其他资质文件 <small class="text-muted">(可选)</small></label>
            {{ document_formset.management_form }}
            <div id="document-form-container">
                {% for form in document_formset %}
                <div class="file-item mt-3 document-form-row {% if form.instance.pk %}existing-document{% else %}new-document{% endif %}" id="document-form-{{ forloop.counter0 }}">
                    <div class="file-info">
                        <i class="fas fa-file-alt file-icon text-info"></i> {# Generic file icon, can be improved with JS #}
                        <div class="file-details">
                            <h6>{{ form.title.value|default:"新文件" }}</h6>
                            <small>{% if form.instance.file %}{{ form.instance.file.name }}{% else %}选择文件{% endif %}</small>
                        </div>
                    </div>
                    <div class="d-flex align-items-center">
                        <div class="me-2">
                            {{ form.title.label_tag }} {{ form.title }}
                            {{ form.file.label_tag }} {{ form.file }}
                            {{ form.description.label_tag }} {{ form.description }}
                            {% if form.instance.pk %}{{ form.id }}{% endif %}
                        </div>
                        {% if form.instance.pk %}
                        <a href="{{ form.instance.file.url }}" target="_blank" class="btn btn-sm btn-outline-primary me-2">
                            <i class="fas fa-eye"></i> 查看
                        </a>
                        {% endif %}
                        <button type="button" class="btn-remove-file remove-document-button">
                            <i class="fas fa-trash"></i>
                        </button>
                        {{ form.DELETE }}
                    </div>
                    {% if form.errors %}
                        <div class="invalid-feedback d-block">
                            {% for field_error in form.errors.values %}
                                {% for error in field_error %}{{ error }}{% endfor %}
                            {% endfor %}
                        </div>
                    {% endif %}
                </div>
                {% endfor %}
            </div>
            <button type="button" class="btn btn-outline-success mt-3" id="add-document-button">
                <i class="fas fa-plus me-2"></i>添加更多文件
            </button>
        </div>
    </div>
    
    <!-- 备注信息 -->
    <div class="form-section">
        <h5><i class="fas fa-sticky-note me-2"></i>备注说明</h5>
        <div class="mb-3">
            <label for="{{ supplier_form.description.id_for_label }}" class="form-label">备注说明</label>
            {{ supplier_form.description }}
            {% if supplier_form.description.errors %}<div class="invalid-feedback d-block">{% for error in supplier_form.description.errors %}{{ error }}{% endfor %}</div>{% endif %}
        </div>
    </div>

    <!-- 提交按钮 -->
    <div class="form-section">
        <div class="d-flex justify-content-between">
            <div>
                <button type="submit" class="btn btn-primary btn-lg">
                    <i class="fas fa-save me-2"></i>{% if supplier %}更新供应商{% else %}创建供应商{% endif %}
                </button>
                <button type="button" class="btn btn-outline-secondary btn-lg ms-2" onclick="resetForm()">
                    <i class="fas fa-undo me-2"></i>重置
                </button>
            </div>
            <div>
                <a href="{% url 'assets:supplier_list' %}" class="btn btn-outline-danger btn-lg">
                    <i class="fas fa-times me-2"></i>取消
                </a>
            </div>
        </div>
    </div>
</form>
    </div>
</div>

<script>
// File upload related variables
let uploadedDocuments = [];
let removedDocuments = []; // This will now be handled by formset DELETE checkbox

// Page load initialization
document.addEventListener('DOMContentLoaded', function() {
    initializeFormset();
    // The old file upload JS needs to be adapted or removed.
    // For now, I'll comment out the old file upload initialization
    // initializeFileUpload();
    initializeFormValidation();
});

// Initialize formset for dynamic document forms
function initializeFormset() {
    const formContainer = document.getElementById('document-form-container');
    const addButton = document.getElementById('add-document-button');
    let totalForms = document.querySelector('#id_documents-TOTAL_FORMS');

    addButton.addEventListener('click', function() {
        const currentForms = document.querySelectorAll('.document-form-row').length;
        const newForm = formContainer.children[0].cloneNode(true); // Clone the first form as a template

        // Clear values and update names/ids for new form
        newForm.querySelectorAll('input, textarea, select').forEach(input => {
            const name = input.name.replace(/-\d+-/, `-${currentForms}-`);
            const id = input.id.replace(/-\d+-/, `-${currentForms}-`);
            input.name = name;
            input.id = id;
            input.value = ''; // Clear value for new form
            if (input.type === 'checkbox') {
                input.checked = false;
            }
        });
        newForm.id = `document-form-${currentForms}`;
        newForm.classList.remove('existing-document');
        newForm.classList.add('new-document');
        newForm.style.display = 'block'; // Ensure it's visible

        // Update DELETE checkbox for new form
        const deleteCheckbox = newForm.querySelector('input[type="checkbox"][name$="-DELETE"]');
        if (deleteCheckbox) {
            deleteCheckbox.checked = false;
        }

        formContainer.appendChild(newForm);
        totalForms.value = parseInt(totalForms.value) + 1;

        // Re-attach event listeners for new form's remove button
        newForm.querySelector('.remove-document-button').addEventListener('click', function() {
            removeDocumentForm(newForm);
        });
    });

    // Attach event listeners for existing remove buttons
    document.querySelectorAll('.remove-document-button').forEach(button => {
        button.addEventListener('click', function() {
            const formRow = this.closest('.document-form-row');
            removeDocumentForm(formRow);
        });
    });
}

function removeDocumentForm(formRow) {
    const deleteCheckbox = formRow.querySelector('input[type="checkbox"][name$="-DELETE"]');
    if (deleteCheckbox) {
        deleteCheckbox.checked = true;
        formRow.style.display = 'none'; // Hide the form row
    } else {
        formRow.remove(); // For newly added forms without a DELETE checkbox
    }
}

// Old file upload functions (to be reviewed and potentially removed/adapted)
// function initializeFileUpload() { ... }
// function handleLicenseUpload(file) { ... }
// function handleDocumentsUpload(files) { ... }
// function validateFile(file, allowedTypes, maxSizeMB) { ... }
// function createFilePreview(file, type, index = null) { ... }
// function getFileIcon(filename) { ... }
// function removeLicensePreview() { ... }
// function removeLicense() { ... }
// function removeDocumentPreview(index) { ... }
// function removeExistingDocument(docId) { ... }

// Reset form (needs adaptation for formsets)
function resetForm() {
    if (confirm('确定要重置表单吗？所有未保存的数据将丢失。')) {
        document.getElementById('supplierForm').reset();
        // Reset formset forms
        const formContainer = document.getElementById('document-form-container');
        while (formContainer.children.length > 1) { // Keep one empty form for new entries
            formContainer.removeChild(formContainer.lastChild);
        }
        const firstForm = formContainer.children[0];
        firstForm.querySelectorAll('input, textarea, select').forEach(input => {
            input.value = '';
            if (input.type === 'checkbox') {
                input.checked = false;
            }
        });
        document.querySelector('#id_documents-TOTAL_FORMS').value = 1; // Reset total forms

        // Re-show hidden deleted forms if any
        document.querySelectorAll('.document-form-row[style*="display: none"]').forEach(row => {
            row.style.display = 'block';
            const deleteCheckbox = row.querySelector('input[type="checkbox"][name$="-DELETE"]');
            if (deleteCheckbox) {
                deleteCheckbox.checked = false;
            }
        });
        
        // Re-show current license if it was hidden
        const currentLicense = document.getElementById('currentLicense');
        if (currentLicense) {
            currentLicense.style.display = 'flex';
            const removeLicenseInput = document.querySelector('input[name="remove_license"]');
            if (removeLicenseInput) {
                removeLicenseInput.remove();
            }
        }
        
        // Clear license preview
        document.getElementById('licensePreview').innerHTML = '';
        document.getElementById('business_license').value = '';
    }
}

// Initialize form validation (keep as is for now, will be handled by Django forms)
function initializeFormValidation() {
    // Django forms handle most validation.
    // Client-side validation for email/URL can remain if desired.
    const form = document.getElementById('supplierForm');
    form.addEventListener('submit', function(e) {
        // Example: if you still want custom JS validation for specific fields
        // if (!validateCustomFields()) {
        //     e.preventDefault();
        // }
    });
}

// Custom validation functions (can be kept or removed if Django forms suffice)
function validateCustomFields() {
    const email = document.getElementById('id_email').value.trim(); // Use id_email for Django form field
    if (email && !isValidEmail(email)) {
        alert('请输入正确的邮箱地址');
        document.getElementById('id_email').focus();
        return false;
    }
    
    const website = document.getElementById('id_website').value.trim(); // Use id_website for Django form field
    if (website && !isValidUrl(website)) {
        alert('请输入正确的网站地址');
        document.getElementById('id_website').focus();
        return false;
    }
    return true;
}

function isValidEmail(email) {
    const emailRegex = /^[^
@]+@[^
@]+\.[^
@]+$/;
    return emailRegex.test(email);
}

function isValidUrl(url) {
    try {
        new URL(url);
        return true;
    } catch {
        return false;
    }
}
</script>
{% endblock %}